// gwc.ts
import { defineStore } from 'pinia';

export const useGwcStore = defineStore('gwc', {
  state: () => ({
    gwcs: [] as any[],  // 存储购物车商品
  }),
  actions: {
    // 更新购物车
    addProductToCart(product: any) {
      this.gwcs.push(product);
      this.saveToLocalStorage(); // 更新本地存储
    },

    // 设置购物车商品
    setCartItems(items: any[]) {
      this.gwcs = items; // 直接赋值
      this.saveToLocalStorage(); // 更新本地存储
    },

    // 从购物车中删除商品
    removeProductFromCart(productId: string) {
      this.gwcs = this.gwcs.filter(item => item.id !== productId);
      this.saveToLocalStorage(); // 更新本地存储
    },

    // 清空购物车
    clearCart() {
      this.gwcs = [];
      this.saveToLocalStorage(); // 清空本地存储
    },

    // 保存购物车到本地存储
    saveToLocalStorage() {
      localStorage.setItem('gwcs', JSON.stringify(this.gwcs));
    },

    // 在 Pinia store 中
    loadFromLocalStorage() {
      const storedCart = localStorage.getItem('gwcs');
      if (storedCart) {
        try {
          this.gwcs = JSON.parse(storedCart);
        } catch (error) {
          console.error('Failed to parse localStorage data:', error);
          this.gwcs = [];
        }
      }
    },

    // 获取购物车商品
    getCartItems() {
      return this.gwcs;
    },

    // 按店铺分组商品
    groupCartItemsByStore() {
      const grouped = this.gwcs.reduce((acc, item) => {
        if (!acc[item.storeName]) {
          acc[item.storeName] = {
            storeName: item.storeName,
            selected: false,
            items: []
          };
        }
        acc[item.storeName].items.push(item);
        return acc;
      }, {});

      return Object.values(grouped);
    }
  },
});
